package com.oj.friend.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.oj.common.security.exception.ServiceExpection;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.oj.common.core.constants.CacheConstants;
import com.oj.common.core.enums.ResultCode;
import com.oj.common.redis.service.RedisService;
import com.oj.friend.domain.question.Question;
import com.oj.friend.mapper.QuestionMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author bin
 * @Date 2025/6/24
 */
@Component
public class QuestionCacheManager {

    @Resource
    private RedisService redisService;

    @Resource
    private QuestionMapper questionMapper;

    public Long getListSize() {
        return redisService.getListSize(CacheConstants.QUESTION_LIST);
    }

    public void refreshCache() {
        List<Question> questions = questionMapper.selectList(new LambdaQueryWrapper<Question>().select(Question::getQuestionId).orderByDesc(Question::getCreateTime));
        if (CollectionUtil.isEmpty(questions)) {
            return;
        }
        List<Long> questionIds = questions.stream().map(Question::getQuestionId).toList();
        // 尾插法
        redisService.rightPushAll(CacheConstants.QUESTION_LIST, questionIds);
    }

    public Long getPreQuestion(Long questionId) {
//        List<Long> questionIds = redisService.getCacheObject(CacheConstants.QUESTION_LIST, List.class);
//        if (CollectionUtil.isEmpty(questionIds)) {
//            return null;
//        }
        Long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST, questionId);
        if (index == 0) {
            throw new ServiceExpection(ResultCode.FAILED_FIRST_QUESTION);
        } else {
            // 中间返回前一个questionId
            // 也可以直接从redis中拿出List<> 再使用Java原生方法找位置并返回前后位置id
            return redisService.indexForList(CacheConstants.QUESTION_LIST, index - 1, Long.class);
        }
    }

    public Long nextQuestion(Long questionId) {
//        List<Long> questionIds = redisService.getCacheObject(CacheConstants.QUESTION_LIST, List.class);
//        if (CollectionUtil.isEmpty(questionIds)) {
//            return null;
//        }
        Long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST, questionId);
        if (index == getListSize() - 1) {
            throw new ServiceExpection(ResultCode.FAILED_LAST_QUESTION);
        } else {
            // 中间返回后一个questionId
            return redisService.indexForList(CacheConstants.QUESTION_LIST, index + 1, Long.class);
        }
    }
}
